package com.xckj.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        List<DataItem> dataList = getData(); // 获取数据列表

        List<DataItem> childList = createChildObjects(dataList, null);

        for (DataItem item : childList) {
            printDataItem(item, 0);
        }
    }

    private static List<DataItem> createChildObjects(List<DataItem> dataList, String parentId) {
        List<DataItem> childList = new ArrayList<>();

        for (DataItem item : dataList) {
            if (item.getParentId() == parentId) {
                List<DataItem> children = createChildObjects(dataList, item.getId());
                item.setChildren(children);
                childList.add(item);
            }
        }

        return childList;
    }

    private static void printDataItem(DataItem item, int level) {
        StringBuilder indent = new StringBuilder();
        for (int i = 0; i < level; i++) {
            indent.append("  ");
        }

        System.out.println(indent.toString() + "Name: " + item.getName());

        List<DataItem> children = item.getChildren();
        if (children != null) {
            for (DataItem child : children) {
                printDataItem(child, level + 1);
            }
        }
    }

    private static List<DataItem> getData() {
        // 模拟数据
        List<DataItem> dataList = new ArrayList<>();
        dataList.add(new DataItem("1", "Parent 1", null));
        dataList.add(new DataItem("2", "Child 1-1", "1"));
        dataList.add(new DataItem("2.1", "Child 1-1-1", "1"));
        dataList.add(new DataItem("3", "Grandchild 1-1-1", "2"));
        dataList.add(new DataItem("4", "Parent 2", null));
        dataList.add(new DataItem("5", "Child 2-1", "4"));

        return dataList;
    }

    // 数据项类
    static class DataItem {
        private String id;
        private String name;
        private String parentId;
        private List<DataItem> children;

        public DataItem(String id, String name, String parentId) {
            this.id = id;
            this.name = name;
            this.parentId = parentId;
            this.children = new ArrayList<>();
        }

        public String getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        public String getParentId() {
            return parentId;
        }

        public List<DataItem> getChildren() {
            return children;
        }

        public void setChildren(List<DataItem> children) {
            this.children = children;
        }
    }
}
